import { Article, Channels } from '@/types/data'
import { ArticleAction, ChannelAction } from '@/types/store'

type State = {
  [key: number]: {
    timestamp: number,
    articles: Article[]
  }
}
// 初始值
const initState = {
  // 1: {
  //   timestamp: 1000,
  //   articles:[{},{}]
  // }
} as State

export default function article (state = initState, action: ArticleAction) {
  console.log(action)
  if (action.type === 'article/setArticle') {
    const { articles, channelId, timestamp } = action.payload
    const oldObj = state[channelId]
    if (oldObj) {
      oldObj.articles.push(...articles)
      oldObj.timestamp = timestamp
      const t = { ...state, [channelId]: { ...oldObj } }
      console.log('t', t)
      return t
    } else {
      const t = { ...state, [channelId]: { timestamp, articles } }
      console.log('t', t)
      return t
    }
  } else if (action.type === 'article/addNewArticle') {
    // 把文章加在已有的最前面
    const { articles, channelId, timestamp } = action.payload
    const oldArticles = state[channelId].articles
    const newArticles = [...articles, ...oldArticles]
    return { ...state, [channelId]: { timestamp, articles: newArticles } }
  }
  return state
}
